const fs = require('fs')
const path = require('path')

// const targetFile = path.join(__dirname, '../file/image.jpeg')
// const recordFile = path.join(__dirname, '../file/image.ce')
const list = []
class Record {
  constructor(recordFile, Etag, size, chunkSize = 1024 * 10) {
    this.path = recordFile
    this.Etag = Etag
    this.size = size
    this.chunkSize = chunkSize
    this.record = ''
    this.chunks = []
    // init
    this.deleteFile()
    this.writeRecordFile()
  }

  readRecordFile() {
    /**
     *
     */
    // console.log(123, this.path, this.record)
    this.record = fs.readFileSync(this.path).toString('utf-8')

    // chunks
    this.chunks = this.record
      .split('\r\n')
      .slice(1) // remove Etag
      .filter(chunk => chunk) // clear null
      .map(chunk => {
        // set {}
        let [index, size, begin, end, read] = chunk.split(' ')
        return {
          index: index - 0,
          size: size - 0,
          begin: begin - 0,
          end: end - 0,
          read: read - 0
        }
      })
    return this.record
  }

  deleteFile() {
    // delete record file
    let record = fs.existsSync(this.path)
    record &&
      fs.unlinkSync(this.path, function(err) {
        if (err) throw err
      })
  }

  writeRecordFile(buffer) {
    buffer = buffer || this.initCeContent()
    //
    this.deleteFile()
    fs.open(this.path, 'as+', (err, fd) => {
      fs.writeSync(fd, buffer, 0, err => {
        if (err) throw err
      })
    })
  }

  checkNullChunk() {
    return this.chunks
      .filter(chunk => !(chunk.read - 0))
      .map(chunk => chunk.index)
  }

  getChunkSize(chunkIndex) {
    // return chunkIndex chunkSize startBit endBit readSize
  }

  setChunkTag(chunkIndex, over = true) {
    if (Array.isArray(chunkIndex)) {
      chunkIndex.map(item => {
        this.chunks[item].read = over - 0
      })
    } else if (typeof chunkIndex === 'number') {
      this.chunks[chunkIndex].read = over - 0
    } else {
      console.log('type error')
      return
    }

    // 写入到文件中，(扩展成，多次事件整合成一次来执行)

    list.push(this.resetCeContent)

    setImmediate(() => {
      list.length && this.resetCeContent()
      list.length = 0
    })
  }

  initCeContent(contentLength) {
    // result
    let result = `${this.Etag}\r\n`
    const length = Math.ceil(this.size / this.chunkSize)
    // chunk-download
    for (let i = 0; i < length; i++) {
      let start = i * this.chunkSize
      let end = i === length - 1 ? this.size - 1 : (i + 1) * this.chunkSize - 1

      result += `${i} ${end - start} ${start} ${end} 0\r\n`
    }

    return result
  }

  resetCeContent() {
    // result
    let result = `${this.Etag}\r\n`

    // chunk-download
    for (let i = 0, length = this.chunks.length; i < length; i++) {
      let { index, size, begin, end, read } = this.chunks[i]
      result += `${index} ${size} ${begin} ${end} ${read}\r\n`
    }
    // console.log(result)
    this.writeRecordFile(result)
  }
}

/**
 * .ce文件 格式
 * Etag\r\n
 * chunkIndex chunkSize startBit endBit readSize 0\r\n
 * chunkIndex chunkSize startBit endBit readSize 0\r\n
 * chunkIndex chunkSize startBit endBit readSize 0\r\n
 * chunkIndex chunkSize startBit endBit readSize 0\r\n
 * .....
 */

// let record = new Record(recordFile, 'FF70503A7175D736D973ECE83554EE84', 706587)

// // record.setChunkTag(68)
// setTimeout(() => {
//   record.readRecordFile()
//   console.log(record)
//   record.setChunkTag([68, 67])
// }, 1000)

// console.log(record.chunks)

module.exports = Record
